package pkgs;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.net.MalformedURLException;

import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.SnapshotParameters;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.ImageInput;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;

public class javafxUtil  extends javafx.application.Application{
	
	public static void main(String[] args) {
		javafx.application.Application.launch(args);
	}

	public static String topImg;
	public static String lowImg;
	public static RenderedImage bi_sketch;

	@Override
	public void start(Stage Stage1) throws Exception {
		bi_sketch=blend_jfx(topImg,lowImg,BlendMode.COLOR_DODGE);
		Stage1.setTitle("Image Write Test");
//		if(scene==null)
//			throw new RuntimeException("scene is null");
//		Stage1.setScene(scene);
 		Stage1.show();
 		Stage1.close();
	}

	public static BufferedImage blend_jfx(String topImg,

			String lowImg, BlendMode BlendMode1) throws MalformedURLException {
	 
		Blend blend = new Blend(BlendMode1);
		blend.setTopInput(new ImageInput(new Image(new File(topImg).toURI().toURL().toString() )));
		blend.setBottomInput(new ImageInput(new Image(new File(lowImg).toURI().toURL().toString())));

		Group grp = new Group();

		grp.setEffect(blend);

		WritableImage img2 = grp.snapshot(new SnapshotParameters(), null);

		BufferedImage copy2 = SwingFXUtils.fromFXImage(img2, null);
		  copy2 = Remove_alpha_channel(copy2);
		return copy2;
	}
	
	
	public static BufferedImage Remove_alpha_channel(BufferedImage copy2) {
		// Get buffered image:
		BufferedImage image = copy2;

		// Remove alpha-channel from buffered image:
		BufferedImage imageRGB = 
		  new BufferedImage(
		    image.getWidth(), 
		    image.getHeight(), 
		    BufferedImage.OPAQUE); 

		Graphics2D graphics = imageRGB.createGraphics();

		graphics.drawImage(
		  image, 
		  0, 
		  0, 
		  null);
		return imageRGB;
	}

	public static BufferedImage blend(String topImg, String lowImg, BlendMode BlendMode1) {
		javafxUtil.topImg=topImg;
		javafxUtil.lowImg=lowImg;
		javafx.application.Application.launch(null);
		return (BufferedImage) javafxUtil.bi_sketch;
	}

}
